<!--
 * @Descripttion: 编辑采购模板
 * @Author: xiao li
 * @Date: 2020-12-09 11:03:19
 * @LastEditors: xiao li
 * @LastEditTime: 2021-11-19 17:20:35
-->
<template>
  <div class="lb-add-classify">
    <top-nav :title="navTitle" :isBack="true" />
    <div class="form-search">
      <div style="height: 40px"></div>
      <el-form
        @submit.native.prevent
        :model="subForm"
        ref="subForm"
        :rules="subFormRules"
        label-width="120px"
      >
        <el-form-item label="模板名称" prop="title">
          <el-input
            v-model="subForm.title"
            placeholder="请输入模板名称"
            maxlength="20"
            show-word-limit
          ></el-input>
        </el-form-item>
        <el-form-item label="模板副标题" prop="sub_title">
          <el-input
            type="text"
            v-model="subForm.sub_title"
            placeholder="请输入模板副标题"
            maxlength="20"
            show-word-limit
          ></el-input>
        </el-form-item>
        <el-form-item label="模板封面" prop="cover">
          <lb-cover
            :fileList="subForm.cover"
            @selectedFiles="getCover"
          ></lb-cover>
          <lb-tool-tips
            >图片建议尺寸: 686 * 280，小程序转发出去显示的封面图</lb-tool-tips
          >
        </el-form-item>
        <el-form-item label="选择分类" prop="cate">
          <el-cascader
            collapse-tags
            v-model="subForm.cate"
            :options="options.cate"
            @change="choiceAllCompanyItem($event, 'cate', 'copyCateId')"
            :props="{
              multiple: true,
              checkStrictly: true,
              label: 'title',
              value: 'id'
            }"
            clearable
          ></el-cascader>
        </el-form-item>
        <el-form-item label="选择公司" prop="company">
          <el-cascader
            collapse-tags
            v-model="subForm.company"
            :options="options.company"
            @change="choiceAllCompanyItem($event, 'company', 'copyCompanyId')"
            :props="{
              multiple: true,
              checkStrictly: true,
              label: 'name',
              value: 'id'
            }"
            clearable
          ></el-cascader>
        </el-form-item>
        <el-form-item label="排序值" prop="top">
          <el-input-number
            class="lb-input-number"
            v-model="subForm.top"
            :controls="false"
            :precision="0"
            :min="0"
            placeholder="请输入排序值"
          ></el-input-number>
          <lb-tool-tips>值越大, 排序越靠前</lb-tool-tips>
        </el-form-item>
        <el-form-item>
          <lb-button type="primary" @click="submitInfo">{{
            $t('action.submit')
          }}</lb-button>
          <lb-button @click="$router.back(-1)">{{
            $t('action.back')
          }}</lb-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
export default {
  data () {
    return {
      id: '',
      navTitle: '',
      options: {},
      companyResult: {
        cate: [],
        company: []
      },
      subForm: {
        id: 0,
        title: '',
        sub_title: '',
        cover: '',
        cate: [],
        copyCateId: [],
        company: [],
        copyCompanyId: [],
        public_cate: 0,
        public_company: 0,
        top: '',
        status: 1
      },
      subFormRules: {
        title: { required: true, type: 'string', message: '请输入模板名称', trigger: 'blur' },
        sub_title: { required: true, type: 'string', message: '请输入模板副标题', trigger: 'blur' },
        cover: { required: true, type: 'array', message: '请上传图片', trigger: 'blur' },
        cate: { required: true, type: 'array', message: '请选择分类', trigger: 'change' },
        company: { required: true, type: 'array', message: '请选择公司', trigger: 'change' },
        top: { required: true, type: 'number', message: '请输入排序值', trigger: 'blur' }
      }
    }
  },
  async created () {
    let { id } = this.$route.query
    await this.getSelectOptions()
    if (id) {
      this.subForm.id = id
      await this.getDetail(id)
    }
    this.navTitle = this.$t(id ? 'menu.PurchaseEdit' : 'menu.PurchaseAdd')
  },
  methods: {
    getSelectOptions () {
      this.$api.GoodsListSelectV2().then(res => {
        if (res.code === 200) {
          let { data } = res
          this.handleCompanyOptions(data.cate, [], 'cate')
          this.handleCompanyOptions(data.company, [], 'company')
          data.cate.length && data.cate.unshift({
            id: 0,
            title: '全选'
          })
          data.company.length && data.company.unshift({
            id: 0,
            name: '全选'
          })
          this.options = data
        }
      })
    },
    handleCompanyOptions (data, arr = [], key) {
      for (let i = 0, len = data.length; i < len; i++) {
        let newArr = JSON.parse(JSON.stringify(arr))
        newArr.push(data[i].id)
        this.companyResult[key].push(JSON.parse(JSON.stringify(newArr)))
        if (data[i].children && data[i].children.length > 0) {
          this.handleCompanyOptions(data[i].children, newArr, key)
        }
      }
    },
    /**
     * @method 全选公司
     */
    choiceAllCompanyItem (val, key, copykey) {
      let companyResult = this.companyResult[key]
      // true = 添加  false 取消、减少
      let rType = val.length > this.subForm[copykey].length
      let firstVal = val[0] && val[0][0]
      if (rType) {
        // 添加
        if (firstVal && val.length === companyResult.length) {
          // 其他都选完了，就只有全选没选了
          this.subForm[key] = [[0], ...val]
        } else if (firstVal === 0) {
          this.subForm[key] = [[0], ...companyResult]
        }
      } else {
        // 减少
        if (firstVal === 0) {
          // 第一个为0 只取消全选
          let copyArr = JSON.parse(JSON.stringify(val))
          copyArr.splice(0, 1)
          this.subForm[key] = copyArr
        } else if (val.length === companyResult.length) {
          // 清空
          this.subForm[key] = []
        } else {
          this.subForm[key] = val
        }
      }
      this.subForm[copykey] = this.subForm[key]
    },

    /**
     * @method 获取封面图
     */
    getCover (img) {
      this.subForm.cover = img
    },
    async getDetail (id) {
      let { code, data } = await this.$api.purchaseInfo({ id })
      if (code !== 200) return
      data.cover = [{ url: data.cover }]
      let copyCompany = JSON.parse(JSON.stringify(data.company))
      data.company = data.public_company === 1
        ? [[0], ...copyCompany]
        : copyCompany
      data.copyCompanyId = data.company
      let copyCate = JSON.parse(JSON.stringify(data.cate))
      data.cate = data.public_cate === 1
        ? [[0], ...copyCate]
        : copyCate
      data.copyCateId = data.cate

      for (let key in this.subForm) {
        this.subForm[key] = data[key]
      }
    },
    /**
     * @method 新增/编辑模板
     */
    submitInfo () {
      let flag = true
      this.$refs['subForm'].validate(valid => {
        if (!valid) flag = false
      })
      if (flag) {
        let subForm = this.$util.pick(this.subForm, [
          'id', 'title', 'sub_title', 'cover', 'cate', 'company', 'top', 'status'
        ])
        subForm.cover = subForm.cover[0].url
        if (subForm.company[0][0] === 0) {
          subForm.company.splice(0, 1)
          subForm.public_company = 1
        } else {
          subForm.public_company = 0
        }
        if (subForm.cate[0][0] === 0) {
          subForm.cate.splice(0, 1)
          subForm.public_cate = 1
        } else {
          subForm.public_cate = 0
        }
        let modelMethod = subForm.id ? 'purchaseUpdate' : 'purchaseAdd'
        this.$api[modelMethod](subForm).then(res => {
          if (res.code === 200) {
            this.$message.success(this.$t(subForm.id ? 'tips.successRev' : 'tips.successSub'))
            this.$router.back(-1)()
          }
        })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.lb-add-classify {
  width: 100%;
  .form-search {
    padding: 20px;
    .el-form {
      width: 100%;
      .el-form-item {
        margin-bottom: 24px;
        .el-select,
        .el-input-number,
        .el-input,
        .el-cascader {
          width: 300px;
        }
      }
      .last-form-item {
        margin-top: 30px;
      }
      .item-tips {
        margin-left: 120px;
        margin-bottom: 24px;
        color: #999999;
      }
    }
  }
}
</style>
